//
//  ZYConsultView.m
//  Tourism
//
//  Created by 张亚 on 16/1/23.
//  Copyright © 2016年 zhikuiyu. All rights reserved.
//

#import "ZYConsultView.h"
#import "ZYChatMode.h"
#import "ZYChatFrame.h"
#import "ZYChatCell.h"

@interface ZYConsultView ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{
    UITableView * tabView;
}
@property (nonatomic,strong) NSMutableArray * chatFrames;

@property (nonatomic,strong) NSDictionary * receiverMessage;

@end

@implementation ZYConsultView

- (NSMutableArray *)chatFrames{

    if (_chatFrames == nil) {
        NSString * path = [[NSBundle mainBundle]pathForResource:@"messages.plist" ofType:nil];
        NSMutableArray * dictArray = [NSMutableArray arrayWithContentsOfFile:path];
        
        NSMutableArray * mfArray = [NSMutableArray array];
        for (NSDictionary * dict in dictArray) {
            
            ZYChatMode * mode = [ZYChatMode chatWithDict:dict];
            //判断时间是否一致 相同就隐藏起来
            ZYChatFrame * lastMF = [mfArray lastObject];
            ZYChatMode * lastMsg = lastMF.chatMode;
            
            mode.hideTime = [mode.time isEqualToString:lastMsg.time];
            
            ZYChatFrame * cf = [[ZYChatFrame alloc]init];
            cf.chatMode = mode;
            
            [mfArray addObject:cf];
        }
        _chatFrames = mfArray;
    }
    return _chatFrames;
}
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor clearColor];
        [self configure];
    }
    return self;
}

- (void)configure{
    [self createdTableView];
    [self createdBottomView];
    //监听键盘的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(KeyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)KeyboardWillChangeFrame:(NSNotification *)note{
    NSLog(@"%@",note.userInfo);
    //键盘弹出
    //1、取得键盘最后的frame
    CGRect keyboardFrame = [note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //2、计算控制器的View需要平移的距离
    CGFloat transformY = keyboardFrame.origin.y - SCREEN_HEIGHT;//结果是负值（这样才能保证视图向上平移）(!!!!注意 键盘上和视图位置没关系)
    //3、动画效果
    CGFloat duration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];//取出键盘内部动画时间（也可以自己直接定义）
    [UIView animateWithDuration:duration animations:^{
        self.transform = CGAffineTransformMakeTranslation(0, transformY);
    }];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self endEditing:YES];
}
- (void)createdTableView{
    tabView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.bounds.size.height - 44) style:UITableViewStylePlain];
    tabView.dataSource = self;
    tabView.delegate = self;
    //取出分割线
    tabView.separatorStyle = UITableViewCellAccessoryNone;
    tabView.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1.0];
    //不允许选中
    tabView.allowsSelection = NO;
    [self addSubview:tabView];
    
    //设置控制器UIWindow的颜色（让键盘在弹出的时候没有黑色）
    self.window.backgroundColor = tabView.backgroundColor;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.chatFrames.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //创建cell
    ZYChatCell * cell = [ZYChatCell cellWithTableView:(UITableView *)tableView];
    //给cell传递模型
    cell.chatFrame = self.chatFrames[indexPath.row];
    return cell;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ZYChatFrame * mf = self.chatFrames[indexPath.row];
    return mf.cellHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"sasd");
}

- (void)createdBottomView{
    
    UIView * bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, tabView.frame.size.height, self.frame.size.width, 20)];
    [self addSubview:bottomView];
    
#pragma mark --- 文本框
    UITextField * wordField = [[UITextField alloc]initWithFrame:CGRectMake(40, 4, 250, 36)];
    wordField.background = [UIImage imageNamed:@"chat_bottom_textfield"];
    [bottomView addSubview:wordField];
    wordField.placeholder = @"请输入内容";
    //键盘确认按钮样式
    wordField.returnKeyType = UIReturnKeySend;
    //在我文本框没有输入信息时不能按确认按钮
    wordField.enablesReturnKeyAutomatically = YES;
    //设置代理 在输入结束以后调用代理方法
    wordField.delegate = self;
    //设置文本框左边显示有一定的间隙
    wordField.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 3, 0)];
    wordField.leftViewMode = UITextFieldViewModeAlways;
    
    UIButton * addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(300, 2, 40, 40);
    [addBtn setImage:[UIImage imageNamed:@"chat_bottom_smile_nor"] forState:UIControlStateNormal];
    [addBtn setTitle:@"发送" forState:UIControlStateNormal];
    addBtn.backgroundColor = [UIColor blueColor];
    [bottomView addSubview:addBtn];
}

#pragma mark --- 文本框的代理
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    //输入之后放弃第一响应者
    [textField resignFirstResponder];
    //1、自己发送一条消息
    [self addMessage:textField.text type:ZYChatModeTypeMe];
    //2、模拟接收一条消息
    NSString * receiver = [self receiverWithText:textField.text];
    [self addMessage:receiver type:ZYChatModeTypeOther];
    
    //3、我是利用这种方法清除文字（也可以使用将wordField设为全局变量，然后清除处理）
    textField.text = nil;
    
    return YES;
}


#pragma mark --- 发送消息 -- 并且返回当前行
- (void)addMessage:(NSString *)text type:(ZYChatModeType)type{
    
    //1、取出数据模型
    ZYChatMode * msg = [[ZYChatMode alloc]init];
    msg.type = type;
    msg.text = text;
    //设置数据模型的时间
    NSDate * now = [NSDate date];
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"HH:mm";
    msg.time = [formatter stringFromDate:now];
    
    //判断是否显示时间
    ZYChatFrame * lastMF = [self.chatFrames lastObject];
    ZYChatMode * lastMsg = lastMF.chatMode;
    msg.hideTime = [msg.time isEqualToString:lastMsg.time];
    
    //2、frame模型
    ZYChatFrame * mf = [[ZYChatFrame alloc]init];
    mf.chatMode = msg;          //为什么？？？？？
    [self.chatFrames addObject:mf];
    //3、刷新表格
    [tabView reloadData];
    //4、自动滚动表格到最后一行
    NSIndexPath * lastPath = [NSIndexPath indexPathForRow:self.chatFrames.count - 1 inSection:0];
    [tabView scrollToRowAtIndexPath:lastPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

#pragma mark --- 模拟发送消息
- (NSString *)receiverWithText:(NSString *)text{
    for (int i = 0; i < text.length; i++) {
        NSString * receiver = [text substringWithRange:NSMakeRange(i, 1)];
        if (self.receiverMessage[receiver]) {
            return  self.receiverMessage[receiver];
        }
    }
    return @"你快来阿萨德";
}
#pragma mark --- 模拟接收到的消息存储路径
- (NSDictionary *)receiverMessage{
    if (_receiverMessage == nil) {
        _receiverMessage = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"autoreply.plist" ofType:nil]];
    }
    return _receiverMessage;
}
- (BOOL)prefersStatusBarHidden{
    
    return YES;
}
@end
